package com.situ.allaia.service.impl;

import com.situ.allaia.dao.CategoryDao;
import com.situ.allaia.dao.GoodDao;
import com.situ.allaia.model.Category;
import com.situ.allaia.model.Good;
import com.situ.allaia.service.CategoryService;
import org.springframework.aop.framework.AopContext;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Service
@CacheConfig(cacheNames = "com.situ.allaia.service.impl")
public class CategoryServiceImp implements CategoryService {
    private final CategoryDao categoryDao;
    private final GoodDao goodDao;

    public CategoryServiceImp(CategoryDao categoryDao, GoodDao goodDao) {
        this.categoryDao = categoryDao;
        this.goodDao = goodDao;
    }
    @Cacheable
    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }
    @Cacheable
    @Override
    public Category findById(Integer id) {
        return categoryDao.findById(id);
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean save(Category category) {
        category.setGmtCreate(LocalDateTime.now());
        category.setGmtUpdate(LocalDateTime.now());
        return categoryDao.save(category) > 0;
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean update(Category category) {
        category.setGmtUpdate(LocalDateTime.now());
        return categoryDao.update(category) > 0;
    }
    @CacheEvict(allEntries = true)
    @Override
    public int deleteByIds(Collection<Integer> ids) {
        int sum = 0;
        for (Integer id:ids){
            //不会触发动态代理,不会触发aop
            sum += deleteById(id);
        }
        return sum;
    }
    @CacheEvict(allEntries = true)
    @Override
    public int deleteById(Integer id) {
        if (id == null){
            return 0;
        }
        //获取当前类型的aop动态代理实例
        CategoryService cs = (CategoryService) AopContext.currentProxy();
        //安全删除,调用本类方法,不会触发动态代理的缓存
        List<Category> categories = cs.findAll();
        boolean b = categories.stream().anyMatch(t->id.equals(t.getParentId()));
        //如果有子类别,不能删
        if (b){
            return 0;
        }
        //如果商品属于此类别
        //todo:明天继续
        List<Good> goods = goodDao.findByCategoryId(id);
        if (!goods.isEmpty()){
            return 0;
        }

        return categoryDao.deleteByIds(Set.of(id));
    }
}
